package juc.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/*
* 同步模式之顺序控制
* */
public class Test6 {
   static boolean is2Running=false;
    public static void main(String[] args) {
//      impl1();
//        impl2();
        impl3();
    }
    public static void impl1(){
        Object lock = new Object();
        new Thread(()->{
            synchronized (lock){
                while (!is2Running){
                    System.out.println("等待2打印...");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("打印1...");
            }
        },"t1").start();
        new Thread(()->{
            synchronized (lock){
                System.out.println("打印2...");
                is2Running=true;
                lock.notifyAll();
            }
        },"t2").start();
    }
    public static void impl2(){
        Thread t1 = new Thread(() -> {
            while (!is2Running){
                LockSupport.park();
            }
            System.out.println("打印1.....");
        }, "t1");
        t1.start();
        Thread t2 = new Thread(() -> {
            System.out.println("打印2.....");
            is2Running=true;
            LockSupport.unpark(t1);
        }, "t1");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
    public static void impl3(){
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(()->{
            lock.lock();
            try {
                while (!is2Running){
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("打印1...");
            } finally {
                lock.unlock();
            }
        },"t1").start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            lock.lock();
            try {
                System.out.println("打印2...");
                is2Running=true;
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        },"t2").start();
    }
}
